var ctx=window.daijia.ctx;
var isUpPlatformInfo = window.isUpPlatformInfo;
var isDriverBindPhone = window.isDriverBindPhone == 'true'?true:false;
var jgpt = window.jgpt;
var offset=0;
var limit=20;
var pagingLimit=20;//显示分页时的条数
var currentTotalElements=0;//当前显示总条数


var pageLoading=true;//是否能滚动加载
var hasShowPages=false;//是否已显示分页
var firstLoadPages=true;//分页初始化时 不自动加载

//筛选条件
var search_name=null;
var search_phone=null;
var search_username=null;
var search_startTime=null;
var search_endTime=null;
var search_companyId=[];
var search_virtual=null;
var search_status=[];
var search_type=[];
var search_isFreeze=false;
var search_isPlatform=[];
var search_isLeague=null;

//上传司机ids
var upload_driver = [];

$(document).ready(function(){
	$("#startTime").val("");
	$("#endTime").val("");
	$("#startTime").datetimepicker({ format: 'yyyy-mm-dd', language: 'zh-CN', minView: 'month', pickDate: true, pickTime: false, inputMask: false, autoclose: true });
	$("#endTime").datetimepicker({ format: 'yyyy-mm-dd', language: 'zh-CN', minView: 'month', pickDate: true, pickTime: false, inputMask: false, autoclose: true });
	initdata(false);
	
	var getCheckDriverInfo;
	$("#upload_button").click(function(){
		
		if(isUpPlatformInfo == "false"){
			$.scojs_message("监管平台上传开关已关闭", $.scojs_message.TYPE_ERROR);
			return;
		}
		
		if(upload_driver.length==0){
			$.scojs_message("请选择需要上报的服务人员", $.scojs_message.TYPE_ERROR);
			return false;
		}

		$(".tempInfoStr").remove();
		$(".finish_info").remove();
		$("#progressDiv").show();
		$("#uploadDriverModal .modal-dialog").addClass("modal-sm");
		$("#uploadDriverModal").modal();
		$("#dataCheck").text("数据校验中")
		getCheckDriverInfo = window.setInterval(function(){
			var temp = $("#progressDiv").width();
			var load = $("#loading").width();
			if(load>=temp){
				$("#loading").width(10);
			}else{
				$("#loading").width(load+10);
			}
		},100);

		var param = upload_driver.join(",")
		$.post(ctx+"/driver/checkDriver",{ids:param},function(data){
            if(data.success){
				var str ="<div class='tempInfoStr'>";
				$("#progressDiv").hide();
				clearInterval(getCheckDriverInfo);
				if(data.result.success){
					$("#uploadDriverModal .modal-body").append("<span class='finish_info'>数据校验通过，是否上传？&nbsp<button type='button' id='uploadDriverInfoButton' class='btn btn-info btn-sm' style='padding:2px 10px;''>上传</button></span>");
				}else{
					var index=0;
					for(var key in data.result){
						if(key !="success"){
                          str+=(++index)+": ["+key+"]"+"<br/>";
                          var daataStr = data.result[key].split(',');
						  for(var i=0;i<daataStr.length-1;i++){
							str += "&nbsp&nbsp&nbsp&nbsp"+index+"."+(i+1)+"："+daataStr[i]+"<br/>";
						  }
						}
					}
					$("#uploadDriverModal .modal-dialog").removeClass("modal-sm");
					str+="</div>";
					$("#dataCheck").text("数据校验结果：共计"+index+"位服务人员校验失败");
					$("#uploadDriverModal .modal-body").append(str)
				}
			}

		});

	});
	$(document).on("click",".checkDriverItem",function(event){
		var flag = $(this).attr("flag");
		//console.debug($(this).val());
		if(Boolean.parse(flag)){
			$(this).attr("flag",false);
			upload_driver.remove(parseInt($(this).val()));
		}else{
			$(this).attr("flag",true);
			upload_driver.push(parseInt($(this).val()));
		}
		$(".checkItemInfoLable").remove();
		$(".query-jiant").append("<span class='label label-info checkItemInfoLable' style='position: absolute;right: 80px;margin-top: 10px;'>共选中 : "+upload_driver.length+"条</span>");
		event.stopPropagation();
	});
	
	$(document).on("click","#uploadDriverInfoButton",function(event){
			$("#uploadDriverModal").modal("hide");
    	
			$("#waitUpDriver .modal-body").html("<img src='/assets/img/hook-spinner.gif'/>");
			$("#waitUpDriver").modal();
			if(upload_driver.length==0){
				return false;
			}
			console.debug(upload_driver)
			var param = upload_driver.join(",");

			$.post(ctx+"/driver/uploadDriver",{ids:param},function(data){
				if(data.success){
					$.scojs_message("上报成功", $.scojs_message.TYPE_OK);
					$("#waitUpDriver").modal("hide");
				}else{
					$.scojs_message("上报失败", $.scojs_message.TYPE_ERROR);
					$("#waitUpDriver").modal("hide");
				}
				var s = window.setInterval(function(){
	        		location.reload();
	            }, 1000);
			});
				event.stopPropagation();
			});



		$("#all").click(function(event){
			
			var flag = Boolean.parse($("#all").attr("val"));
			if (flag) {
				$(this).attr("val", false);
				var items = $(".checkDriverItem");
				for(var i= 0,val;val=items[i++];){ 
				$(val).removeAttr("checked");
					$(val).attr("flag",false);
					upload_driver.remove(parseInt($(val).val()));
				}
			} else {
				$(this).attr("val", true);
				var items = $(".checkDriverItem");
		        for(var i= 0,val;val=items[i++];){ 
				  $(val).prop("checked","true");
				  $(val).attr("flag",true);
				  upload_driver.remove(parseInt($(val).val()));
				  
				  upload_driver.push(parseInt($(val).val()));
				}
			}
		    console.debug(upload_driver);
		    $(".query-jiant").append("<span class='label label-info checkItemInfoLable' style='position: absolute;right: 80px;margin-top: 10px;'>共选中 : "+upload_driver.length+"条</span>");
			event.stopPropagation();
		});
	
	
	
	
	$('#companyId').multiselect({
		enableFiltering: true,
	    includeSelectAllOption: true,
	    selectAllText: '全部',
	    selectAllJustVisible: true,
	    maxHeight:300,
	    buttonWidth: '70%',
	    nonSelectedText: '请选择所属公司',
	    nSelectedText: ' - 已选择',
	    numberDisplayed: 4,
	    allSelectedText: '已选择全部'
	});
	
	
	/*$("a").click(function(){
		var url=$(this).attr("href");
		window.location.href=url;
	});*/
	//点击选择时间
	$("#dateRangeButton").click(function(){
		var dropdowncalendar=$(this).parent().find(".dropdown-calendar");
		if(dropdowncalendar.is(':hidden')){
			dropdowncalendar.show();
			if(dropdowncalendar.find(".datepicker").length==0){
				$('#dateRangeCalendar').DatePicker({
					flat: true,
					current: new Date(),
					date: [new Date()],
					calendars: 3,
					mode: 'range',
					starts: 1,
					onChange: function(formated, dates){
						$("#startTime").val(formated[0]);
						$("#endTime").val(formated[1]);
					}
				});
			}
		}
		else{
			dropdowncalendar.hide();
		}
	});
	
	//高级搜索
	$(".query-jiant").click(function(){
		var src=$("#jiant").attr("src");
		if(src.indexOf("jiant2")>=0){
			$("#jiant").attr("src",ctx+"/assets/img/jiant.png");
			$(".choose").slideDown(300);
		}else{
			$("#jiant").attr("src",ctx+"/assets/img/jiant2.png");
			$(".choose").slideUp(300);
		}
	});

	
	//查询
	$("#searchButton").click(function(){
		
		var DATE_FORMAT = /^[0-9]{4}-[0-1]{1}[0-9]{1}-[0-3]{1}[0-9]{1}$/;
		if($("#startTime").val()!=""){
			if(!DATE_FORMAT.test($("#startTime").val())){
			   $.scojs_message("您输入的启始日期格式有误，正确格式如：2012-01-01", $.scojs_message.TYPE_ERROR);
			   return false;
			}
		}
		
		if($("#endTime").val()!=""){
			if(!DATE_FORMAT.test($("#endTime").val())){
				$.scojs_message("您输入的结束日期格式有误，正确格式如：2012-01-01", $.scojs_message.TYPE_ERROR);
				return false;
			}
		}
		
		if($("#startTime").val()!="" && $("#endTime").val()!=""){
			if($("#startTime").val()>$("#endTime").val()){
				 $.scojs_message("启始日期不能大于结束日期", $.scojs_message.TYPE_ERROR);
				 return false;
			}
		}
		if(null!=$("#companyId").val()){
			search_companyId=$("#companyId").val().join(",");
		}
		else{
			search_companyId=[];
		}
		
		search_name=$("#driverName").val();
		search_phone=$("#driverPhone").val();
		search_username=$("#driverNumber").val();
		search_virtual=$("#virtual").val();
		
		search_startTime=$("#startTime").val();
		search_endTime=$("#endTime").val();
		search_isFreeze=$("#freeze").is(':checked');
		var obj = document.getElementsByClassName("isLeague");
		for(var i=0; i<obj.length; i ++){
			if(obj[i].checked){
				search_isLeague = (obj[i].value);
			}
		}

		var typeArr=[];
		$("input[name=type]:checked").each(function(index,element){
			typeArr.push($(element).val());
		});
		if(null!=typeArr && typeArr.length>0){
			search_type=typeArr.join(",");
		}
		else{
			search_type=[];
		}
		
		var statusArr=[];
		$("input[name=status]:checked").each(function(index,element){
			statusArr.push($(element).val());
		});
		if(null!=statusArr && statusArr.length>0){
			search_status=statusArr.join(",");
		}
		else{
			search_status=[];
		}
		
		var isPlatformArr=[];
		$("input[name=isPlatform]:checked").each(function(index,element){
			isPlatformArr.push($(element).val());
		});
		if(null!=isPlatformArr && isPlatformArr.length>0){
			search_isPlatform=isPlatformArr.join(",");
		}
		else{
			search_isPlatform=[];
		}
		
		
		offset=0;
		initdata(false);
		
	});
	
	$(document).on("keydown","body",function(){
		if(window.event.keyCode == 13){
			$("#searchButton").click();
		}
	});
	
	//滚动
//	$(window).scroll(function () {
//        //$(window).scrollTop()这个方法是当前滚动条滚动的距离
//        //$(window).height()获取当前窗体的高度
//        //$(document).height()获取当前文档的高度
//        var bot = 0; //bot是底部距离的高度
//        if ((bot + $(window).scrollTop()) >= ($(document).height() - $(window).height())) {
//           //当底部基本距离+滚动的高度〉=文档的高度-窗体的高度时；
//        	if(pageLoading){
//        		pageLoading=false;
//        		offset+=limit;
//        		initdata(true);
//        	}
//        }
//    });
	
	//导入
	$(".importDriver").click(function(){
          $("#importDriverModal").modal();
	 });
	
	$("#driverExcel").fileinput({
		uploadUrl: ctx+'/driver/importDriver', // you must set a valid URL here else you will get an error
		allowedFileExtensions : ['xls', 'xlsx'],
		overwriteInitial: false,
		dropZoneEnabled:false,
		maxFileSize: 1024*10,
		maxFilesNum: 1,
		language: 'zh',
		dropZoneTitle:"拖拽文件到这里...",
		maxFileCount: 1, //表示允许同时上传的最大文件个数
		enctype: 'multipart/form-data',
		allowedPreviewTypes: ['image'],
		//allowedFileTypes: ['image'],
		slugCallback: function(filename) {
			return filename.replace('(', '_').replace(']', '_');
		}
	}).on("fileuploaded", function(event, data) {

		var  resp = data.response;
		console.debug(resp);
		var str = "<div id='drivermessageInfo' style='margin:-10px 0px 5px 0;word-break:break-all;'";
		if(resp.success){
			str += " class='alert alert-success'>";
			str +="导入完成";
			$("#importDriverModal").modal("hide");
			initdata(false);
		}else{
			str += "class='alert alert-danger'>";
			if(resp.msg != undefined){
				str +=resp.msg;
				console.debug(resp.rowNum);
			}
			if(resp.message){
				str += resp.message;
			}
           if(resp.realnameIndexs && resp.realnameIndexs.length>0){
			  str += "在第["+resp.realnameIndexs.join(",")+"]行记录,真实姓名不能包含非法字符!   <br/>";
		   }
		   if(resp.usernameIndexs && resp.usernameIndexs.length>0){
			   str += "在第["+resp.usernameIndexs.join(",")+"]行记录,工号不能包含非法字符（或已存在）!";
		   }
		   if(resp.nameIndexs && resp.nameIndexs.length>0){
			   str += "在第["+resp.nameIndexs.join(",")+"]行记录,昵称不能包含非法字符!";
		   }
		   if(resp.idCardIndexs && resp.idCardIndexs.length>0){
			   str += "在第["+resp.idCardIndexs.join(",")+"]行记录,身份证号已存在!";
		   }
		   if(resp.phoneIndexs && resp.phoneIndexs.length>0){
			   str += "在第["+resp.phoneIndexs.join(",")+"]行记录,手机号非法（或已存在）!";
		   }
		   if(resp.typeIndexs && resp.typeIndexs.length>0){
			   str += "在第["+resp.typeIndexs.join(",")+"]行记录,员工类型错误，员工类型只能为兼职或全职!";
		   }
		   if(resp.licenseTimeIndexs && resp.licenseTimeIndexs.length>0){
			   str += "在第["+resp.licenseTimeIndexs.join(",")+"]行记录,入职时间错误，格式如：2012/08/08";
		   }
		   if(resp.repeatPhone != undefined){
				var tempStr="";
				for(var key in resp.repeatPhone){
					tempStr += "["+key+"行,"+resp.repeatPhone[key]+"行],";
				}
				tempStr = tempStr.substr(0,tempStr.length-1);
				str += "在第 "+tempStr+"记录,电话号码重复!";
			}
		   if(resp.repeatIdCard != undefined){
				var tempStr="";
				for(var key in resp.repeatIdCard){
					tempStr += "["+key+"行,"+resp.repeatIdCard[key]+"行],";
				}
				tempStr = tempStr.substr(0,tempStr.length-1);
				str += "在第 "+tempStr+"记录,身份证号码重复!";
			}
		   if(resp.repeatUsername != undefined){
				var tempStr="";
				for(var key in resp.repeatUsername){
					tempStr += "["+key+"行,"+resp.repeatUsername[key]+"行],";
				}
				tempStr = tempStr.substr(0,tempStr.length-1);
				str += "在第 "+tempStr+"记录,工号重复!";
			}
		}
        str +="</div>";
		$(".kv-upload-progress").after(str);

	});
	$("#driverExcel").on("filecleared",function(event, data, previewId, index){
		$("#drivermessageInfo").remove();
	});
	
	$("#downloadTemplet").click(function(){
	    var url = $(this).attr("url");
		var downloadFrame = $('#downloadFrame');
		if(downloadFrame.length == 0){
			downloadFrame = $('<iframe id="downloadFrame" src="" style="display:none"></iframe>');
			$('body').append(downloadFrame);
		}
		downloadFrame.attr('src',ctx+url);

	});
	
	
	$("#export_button").click(function(){
		
		window.location=ctx+"/driver/exportDriver?"+"&name="+$("#driverName").val()+
		                "&phone="+$("#driverPhone").val()+"&username="+$("#driverNumber").val()+
		                "&virtual="+$("#virtual").val()+"&companyId="+search_companyId+"&isFreeze="+($("#freeze").is(':checked'))
		                +"&type="+search_type +"&status="+search_status+"&isPlatform="+search_isPlatform+"&startTime="+$("#startTime").val()+"&endTime="+$("#endTime").val();
	});
	
});

Array.prototype.remove=function(val) {
	if(val == null ){
		return false;
	}
	var flag = false;
	for(var i=0,n=0;i<this.length;i++) {
		if(this[i] != val) {
			this[n++]=this[i];
		}else{
			flag = true;
		}
	}
	if(flag){
		this.length-=1;
	}
}

function initdata(isappend){
	
//	showLoading();
	
	$.ajax({
        url : ctx+'/driver/driverListData',
        type:'GET',
        async:false,
        dataType : 'json',
        data : {
        	"name":search_name,
        	"phone":search_phone,
        	"username":search_username,
        	"companyId":search_companyId,
        	"virtual":search_virtual,
        	"startTime":search_startTime,
        	"endTime":search_endTime,
        	"type":search_type,
        	"isFreeze":search_isFreeze,
        	"status":search_status,
        	"isPlatform":search_isPlatform,
        	"pager.offset":offset,
        	"limit":limit,
					"isLeague":search_isLeague
        },
        success : function(result){
        	 $("#all").attr("val","false");
             $("#all").removeAttr("checked");
        	var newcontent = '';
        	var totalElements=result.totalElements;
        	$("#NoData").text("");
        	
        	if(totalElements>0){
        		$(result.content).each(function(index,data){
        			
        			var statusColor="";
        			var mainButton="";
        			var selectButton="";
        			if(data.isFreeze){
        				statusColor="btn-primary";
        				mainButton="<a href='"+ctx+"/driver/edit/"+data.id+"' type='button' class='btn btn-primary btn-xs'>编辑</a>";
        				if(driveredit){
            				selectButton+="<li><a href='javascript:;' data-value="+data.id+" data-value-name="+data.name+" class='btn-link passwordthis'>修改密码</a></li>";
        				}
        				if(driveredit){
            				selectButton+="<li><a href='javascript:;' data-value='"+data.id+"' class='btn-link onlinethis'>上线</a></li>";
        				}
        				if(drivermoneyview){
        					selectButton+= "<li><a href='"+ctx+"/driver/money/"+data.id+"' class='btn-link'>账户明细</a></li>";
							selectButton+= "<li><a href='"+ctx+"/driver/extendDetail/"+data.id+"' class='btn-link'>推广明细</a></li>";
            			}
        				if(rate){
        					selectButton+= "<li><a href='"+ctx+"/rate/listByDriver/"+data.id+"' class='btn-link'>评价</a></li>";
            			}
        				if(driveredit){
            				selectButton+="<li><a href='javascript:;' data-value='"+data.id+"' class='btn-link jiedongthis'>解冻</a></li>";
        				}
        				if(driverdelete){
        					selectButton+= "<li><a href='javascript:;' data-value='"+data.id+"' class='btn-link deletethis'>删除</a></li>";
            			}
        				if(data.deviceType!=null && data.deviceType=="3"){
        					selectButton+= "<li><a href='javascript:;' data-value='"+data.id+"' class='btn-link deviceInfo'>设备信息</a></li>";
        				}
        			}else if(data.status==0){
        				statusColor="btn-primary";
        				mainButton="<a href='"+ctx+"/driver/edit/"+data.id+"' type='button' class='btn btn-primary btn-xs'>编辑</a>";
        				if(driveredit){
            				selectButton+="<li><a href='javascript:;' data-value="+data.id+" data-value-name="+data.name+" class='btn-link passwordthis'>修改密码</a></li>";
        				}
        				if(driveredit && isDriverBindPhone){
        					if(data.udid.length>0){
            					selectButton+= "<li><a href='javascript:;' data-value='"+data.id+"' class='btn-link jiebangthis'>解绑</a></li>";
                			}
        				}
        				if(driveredit){
            				selectButton+="<li><a href='javascript:;' data-value='"+data.id+"' class='btn-link onlinethis'>上线</a></li>";
        				}
        				if(drivermoneyview){
        					selectButton+= "<li><a href='"+ctx+"/driver/money/"+data.id+"' class='btn-link'>账户明细</a></li>";
							selectButton+= "<li><a href='"+ctx+"/driver/extendDetail/"+data.id+"' class='btn-link'>推广明细</a></li>";
            			}
        				if(rate){
        					selectButton+= "<li><a href='"+ctx+"/rate/listByDriver/"+data.id+"' class='btn-link'>评价</a></li>";
            			}
        				if(driveredit){
            				selectButton+="<li><a href='javascript:;' data-value='"+data.id+"' class='btn-link dongjiethis'>冻结</a></li>";
        				}
        				if(driverdelete){
        					selectButton+= "<li><a href='javascript:;' data-value='"+data.id+"' class='btn-link deletethis'>删除</a></li>";
            			}
        				if(data.deviceType!=null && data.deviceType=="3"){
        					selectButton+= "<li><a href='javascript:;' data-value='"+data.id+"' class='btn-link deviceInfo'>设备信息</a></li>";
        				}
        			}else if(data.status==1){
        				statusColor="btn-primary";
        				mainButton="<a href='"+ctx+"/driver/edit/"+data.id+"' type='button' class='btn btn-primary btn-xs'>编辑</a>";
        				if(driveredit){
            				selectButton+="<li><a href='javascript:;' data-value="+data.id+" data-value-name="+data.name+" class='btn-link passwordthis'>修改密码</a></li>";
        				}
        				if(driveredit && isDriverBindPhone){
        					if(data.udid.length>0){
            					selectButton+= "<li><a href='javascript:;' data-value='"+data.id+"' class='btn-link jiebangthis'>解绑</a></li>";
                			}
        				}
        				if(driveredit){
            				selectButton+="<li><a href='javascript:;' data-value='"+data.id+"' class='btn-link powerofflinethis'>强制下线</a></li>";
        				}
        				if(drivermoneyview){
        					selectButton+= "<li><a href='"+ctx+"/driver/money/"+data.id+"' class='btn-link'>账户明细</a></li>";
							selectButton+= "<li><a href='"+ctx+"/driver/extendDetail/"+data.id+"' class='btn-link'>推广明细</a></li>";
            			}
        				if(rate){
        					selectButton+= "<li><a href='"+ctx+"/rate/listByDriver/"+data.id+"' class='btn-link'>评价</a></li>";
            			}
        				if(driveredit){
            				selectButton+="<li><a href='javascript:;' data-value='"+data.id+"' class='btn-link dongjiethis'>冻结</a></li>";
        				}
        				if(driverdelete){
        					selectButton+= "<li><a href='javascript:;' data-value='"+data.id+"' class='btn-link deletethis'>删除</a></li>";
            			}
        				if(data.deviceType!=null && data.deviceType=="3"){
        					selectButton+= "<li><a href='javascript:;' data-value='"+data.id+"' class='btn-link deviceInfo'>设备信息</a></li>";
        				}
        			}else if(data.status==2){
        				statusColor="btn-primary";
        				mainButton="<a href='"+ctx+"/driver/edit/"+data.id+"' type='button' class='btn btn-primary btn-xs'>编辑</a>";
        				if(driveredit){
            				selectButton+="<li><a href='javascript:;' data-value="+data.id+" data-value-name="+data.name+" class='btn-link passwordthis'>修改密码</a></li>";
        				}
        				if(driveredit){
            				selectButton+="<li><a href='javascript:;' data-value='"+data.id+"' class='btn-link powerofflinethis'>强制下线</a></li>";
        				}
        				if(drivermoneyview){
        					selectButton+= "<li><a href='"+ctx+"/driver/money/"+data.id+"' class='btn-link'>账户明细</a></li>";
							selectButton+= "<li><a href='"+ctx+"/driver/extendDetail/"+data.id+"' class='btn-link'>推广明细</a></li>";
            			}
        				if(rate){
        					selectButton+= "<li><a href='"+ctx+"/rate/listByDriver/"+data.id+"' class='btn-link'>评价</a></li>";
            			}
        				if(driveredit){
            				selectButton+="<li><a href='javascript:;' data-value='"+data.id+"' class='btn-link dongjiethis'>冻结</a></li>";
        				}
        				if(driverdelete){
        					selectButton+= "<li><a href='javascript:;' data-value='"+data.id+"' class='btn-link deletethis'>删除</a></li>";
            			}
        				if(data.deviceType!=null && data.deviceType=="3"){
        					selectButton+= "<li><a href='javascript:;' data-value='"+data.id+"' class='btn-link deviceInfo'>设备信息</a></li>";
        				}
        			}else{
        				statusColor="btn-primary";
        				mainButton="<a href='"+ctx+"/driver/edit/"+data.id+"' type='button' class='btn btn-primary btn-xs'>编辑</a>";
        				if(driveredit){
            				selectButton+="<li><a href='javascript:;' data-value="+data.id+" data-value-name="+data.name+" class='btn-link passwordthis'>修改密码</a></li>";
        				}
        				if(driveredit && isDriverBindPhone){
        					if(data.udid.length>0){
            					selectButton+= "<li><a href='javascript:;' data-value='"+data.id+"' class='btn-link jiebangthis'>解绑</a></li>";
                			}
        				}
        				if(driveredit){
            				selectButton+="<li><a href='javascript:;' data-value='"+data.id+"' class='btn-link powerofflinethis'>强制下线</a></li>";
        				}
        				if(drivermoneyview){
        					selectButton+= "<li><a href='"+ctx+"/driver/money/"+data.id+"' class='btn-link'>账户明细</a></li>";
							selectButton+= "<li><a href='"+ctx+"/driver/extendDetail/"+data.id+"' class='btn-link'>推广明细</a></li>";
            			}
        				if(rate){
        					selectButton+= "<li><a href='"+ctx+"/rate/listByDriver/"+data.id+"' class='btn-link'>评价</a></li>";
            			}
        				if(driveredit){
            				selectButton+="<li><a href='javascript:;' data-value='"+data.id+"' class='btn-link dongjiethis'>冻结</a></li>";
        				}
        				if(driverdelete){
        					selectButton+= "<li><a href='javascript:;' data-value='"+data.id+"' class='btn-link deletethis'>删除</a></li>";
            			}
        				if(data.deviceType!=null && data.deviceType=="3"){
        					selectButton+= "<li><a href='javascript:;' data-value='"+data.id+"' class='btn-link deviceInfo'>设备信息</a></li>";
        				}
        			}
        			var allButton="<div class='btn-group'>"+
									mainButton+
								  "<button type='button' class='btn "+statusColor+" btn-xs dropdown-toggle' data-toggle='dropdown' aria-expanded='false'>"+
								    "<span class='caret'></span>"+
								    "<span class='sr-only'>Toggle Dropdown</span>"+
								  "</button>"+
								  "<ul class='dropdown-menu' role='menu'>"+
								  	selectButton+
								  "</ul>"+
								"</div>";
        			
        			
        			
        			//所属公司
            		var companyNameTd="";
            		if(mainCompany){
            			companyNameTd="<td>"+data.companyAbbreviation+"</td>";
            		}
            		
            		
            		var driverChoseLevel="";
            		if(dj){
            			if(data.jobType.indexOf("daijia")!=-1){
                			driverChoseLevel = "<td><span style='color:red;font-weight:700;'>含</span>("+(data.driverLevel==null?"无":data.driverLevel.name)+")</td>";
                		}else{
                			driverChoseLevel = "<td>--</td>";
                		}
            		}
            		
            		var driverChoseLevelCar="";
            		if(zhuan){
	            		if(data.jobType.indexOf("zhuanche")!=-1){
	            			driverChoseLevelCar = "<td><span style='color:red;font-weight:700;'>含</span>("+(data.driverLevelZhuan==null?"无":data.driverLevelZhuan.name)+")</td>";
	            		}else{
	            			driverChoseLevelCar = "<td>--</td>";
	            		}
            		}
            		
            		var driverChoseLevelPaotui="";
            		if(pao){
	            		if(data.jobType.indexOf("paotui")!=-1){
	            			driverChoseLevelPaotui = "<td><span style='color:red;font-weight:700;'>含</span>("+(data.driverLevelPao==null?"无":data.driverLevelPao.name)+")</td>";
	            		}else{
	            			driverChoseLevelPaotui = "<td>--</td>";
	            		}
            		}
            		
            		var driverChoseLevelFreight="";
            		if(freight){
	            		if(data.jobType.indexOf("freight")!=-1){
	            			driverChoseLevelFreight = "<td><span style='color:red;font-weight:700;'>含</span>("+(data.driverLevelFreight==null?"无":data.driverLevelFreight.name)+")</td>";
	            		}else{
	            			driverChoseLevelFreight = "<td>--</td>";
	            		}
            		}
            		
            		var driverChoseLevelZhuanxian="";
            		var driverGrade="";
            		if(zhuanxian){
	            		if(data.jobType.indexOf("zhuanxian")!=-1){
	            			driverChoseLevelZhuanxian = "<td><span style='color:red;font-weight:700;'>含</span>("+(data.driverLevelZhuanxian==null?"无":data.driverLevelZhuanxian.name)+")</td>";
	            		}else{
	            			driverChoseLevelZhuanxian = "<td>--</td>";
	            		}
	            		driverGrade = "<td>"+data.driverGrade+"</td>";
            		}
            		
            		var posUpdated; 
            		if(data.posUpdated){
            			posUpdated = "<td>"+data.posUpdated+"</td>";
            		}else{
            			posUpdated="<td>未上传</td>";
            		}
            		var appVersion;
            		if(data.appVersion){
            			appVersion = "<td>"+data.appVersion+"</td>";
            		}else{
            			appVersion = "<td>未登录</td>";
            		}
            		var status;
            		if(data.isFreeze){
            			status = "<td><b><span style='color:#4864B0'>冻结</span></b></td>";
            		}else if(data.status==0){
            			status = "<td><span style='color:#999999'>下线</span></td>";
            		}else if(data.status==1){
            			status = "<td><span style='color:#059405;font-weight:700;'>空闲</span></td>";
            		}else if(data.status==2){
            			status = "<td><span style='color:#db871b;font-weight:700;'>派单</span></td>";
            		}else{
            			status = "<td><span style='color:#b40000;font-weight:700;'>忙碌</span></td>";
            		}
            		
            		var photoImg="";
            		var photo=data.photo;
            		if(null!=photo && photo!="" && data.photoExixts){
            			photoImg="<img style='margin-right:5px;' src='"+ctx+"/upload/driver/"+photo+"' class='img-circle' width='30' height='30' />";
            		}
            		else{
            			photoImg="<span style='margin-left:30px;margin-right:5px;'></span>";
            		}
            		
            		//选择上传的对象
            		var checkFlag = false;
					for(var i= 0;val=upload_driver[i++];){
						if(val == data.id){
							checkFlag = true;
						}
					}
            		var tempStr = "";
					// if(data.jobType.indexOf("zhuanche")!=-1){
						tempStr ="<div style='margin-top:0px;'>"+
									"<input id='"+data.id+"' class='checkDriverItem' flag='"+(checkFlag?"true":"false")+"' "+(checkFlag?"checked":"")+" value='"+data.id+"' type='checkbox' />"+
									"<label for='"+data.id+"'>"+
									"</label>"+
							      "</div>"
					// }
            		var upStatus = "";
            		if(data.upStatus == 1){
            			upStatus = "√";
            		}
            		var tempStrString = "";
            		var upStatusString = "";
					if(jgpt){
						tempStrString = "<td>"+ tempStr+"</td>";
						upStatusString = "<td style='text-align: center'>"+ upStatus+"</td>"
					}
						
	    newcontent+="<tr class='grid-data tr-hui' style='display:none;'>"+
	     				tempStrString+
						"<td>"+allButton+"</td>"+
						upStatusString+
						"<td>"+photoImg+data.realname+"</td>"+
						"<td>"+data.username+"</td>"+
						"<td>"+data.name+"</td>"+
						"<td>"+data.phone+"</td>"+
						"<td><span style='color:#ff950b;font-weight:700;'>"+data.virtual+"</span></td>"+
						"<td>"+data.type+"</td>"+
								status+
							   driverChoseLevel+
							   driverChoseLevelCar+
							   driverChoseLevelPaotui+
							   driverChoseLevelFreight+
							   driverChoseLevelZhuanxian+
							   driverGrade+
							   appVersion+
						"<td>"+data.jobTime+"</td>"+
								companyNameTd+
								posUpdated+
						"<td>"+allButton+"</td>"+
					"</tr>";
        		});
        	}
        	else{
              	 $("#NoData").text("当前页面暂无记录 ");
            }

//        	hideLoading();
        	
        	if(!isappend){
        		$(".table tbody .grid-data").remove();
        	}
        	$(".table tbody").append(newcontent);
        	
        	$(".table tbody .grid-data").each(function(index,element){
        		$(element).fadeIn(200+(index*35));
        	});
        	
        	
        	if(!hasShowPages){
        		if(!isappend){
            		currentTotalElements=result.content.length;
            		pageLoading=true;
            	}
        		else{
            		if(currentTotalElements<totalElements){
            			currentTotalElements+=result.content.length;
            			pageLoading=true;
            		}
            		else{
            			pageLoading=false;
            		}
            	}
        	}

        	if(hasShowPages){
    			firstLoadPages=true;
        		$(".pageshow li a").html("共"+totalElements+" 条数据");
        		$(".pagedata").paging(totalElements, {
        			format: '[< ncnnn >]',
        			perpage: pagingLimit,
        			page:(offset/limit)+1,
        			onSelect: function (page) {
        				limit=pagingLimit;
        				offset=(page-1)*limit;
        				if(!firstLoadPages){
        					initdata(false);
        				}
        				firstLoadPages=false;
        		    	return false;
        			},
        			onFormat: function (type) {
        				switch (type) {
        				case 'block': // n and c
        					if (!this.active)
        						return '';
        					else if (this.value != this.page)
        						return '<li><a href="#">' + this.value + '</a></li>';
        					return '<li class="active"><a href="#">' + this.value + '</a></li>';
        				case 'next': // >
        					return '<li><a href="#">&rsaquo;</a><li>';
        				case 'prev': // <
        						return '<li><a href="#">&lsaquo;</a><li>';
        				case 'first': // [
        						return '<li><a href="#">&laquo;</a><li>';
        				case 'last': // ]
        						return '<li><a href="#">&raquo;</a></li>';
        				}
        			}
        		});
        		
        	}
        	else{
        		//滚动达到pagingLimit条开始显示分页
//        		if(currentTotalElements==pagingLimit){
            		
            		pageLoading=false;
            		hasShowPages=true;
            		
            		$(".pageshow").show();
            		$(".pagedata").show();
            		$(".pageshow li a").html("共"+totalElements+" 条数据");
            		$(".pagedata").paging(totalElements, {
            			format: '[< ncnnn >]',
            			perpage: pagingLimit,
            			onSelect: function (page) {
            				limit=pagingLimit;
            				offset=(page-1)*limit;
            				if(!firstLoadPages){
            					initdata(false);
            				}
            				firstLoadPages=false;
            		    	return false;
            			},
            			onFormat: function (type) {
            				switch (type) {
            				case 'block': // n and c
            					if (!this.active)
            						return '';
            					else if (this.value != this.page)
            						return '<li><a href="#">' + this.value + '</a></li>';
            					return '<li class="active"><a href="#">' + this.value + '</a></li>';
            				case 'next': // >
            					return '<li><a href="#">&rsaquo;</a><li>';
            				case 'prev': // <
            						return '<li><a href="#">&lsaquo;</a><li>';
            				case 'first': // [
            						return '<li><a href="#">&laquo;</a><li>';
            				case 'last': // ]
            						return '<li><a href="#">&raquo;</a></li>';
            				}
            			}
            		});
            		
//            	}
        	}
        	
        }
	});
	
}

function showLoading(){
	if($('#loadblacklayer').length==0){
		var dw = $(".table").width();
		var dh = $(".table").height();
		var backlayer ="<div id='loadblacklayer'><div style='margin-top:"+(dh/2)+"px;margin-left:"+(dw/2)+"px;'><img src='"+ctx+"/assets/css/images/loading.gif' /></div></div>"
		$(".table tbody").append(backlayer);
		$('#loadblacklayer').css({"z-index":"9","background":"#000","opacity":"0.5","position":'absolute',"top":0,"width":dw,"height":dh});
	}
}

function hideLoading(){
	if($('#loadblacklayer').length>0){
		$('#loadblacklayer').remove();
	}
}
Boolean.parse = function (str) {
	switch (str.toLowerCase ()) {
		case "true":
			return true;
		case "false":
			return false;
		default:
			throw new Error ("Boolean.parse: Cannot convert string to boolean.");
	}
};
